package com.chixing.service.impl;

import com.chixing.mapper.CustomerMapper;
import com.chixing.pojo.Customer;
import com.chixing.pojo.CustomerExample;
import com.chixing.service.CustomerService;
import com.chixing.util.AESUtil;
import com.chixing.util.MD5Utils;
import com.chixing.util.RSAUtils;
import com.chixing.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.List;

@Service
public class CustomerServiceImpl implements CustomerService {
  @Autowired
  private CustomerMapper customerMapper;

  private static KeyPair keyPair;

  private final String key = "19win899RSV8e303";


  @Override
  public ServerResult login(Long custumerTel, String custumerPsw) {
//    String newPwd = MD5Utils.formPwd2DBPass(custumerPsw, "1a2b3c4d");
//    System.out.println("server --- psw ：" + newPwd);
    System.out.println("登录--前端--psw--：" + custumerPsw);

    String privateKey = getPrivateKey();
    String newPsw = null;

    try {
      System.out.println("RSA解密中。。");
      //原密码 = 解密方法（密文，私钥）；
      String decrypt = RSAUtils.privateDecrypt(custumerPsw, RSAUtils.getPrivateKey(privateKey));
      System.out.println("解密后的密码：" + decrypt);
      //AES 加密
      String encrypt = AESUtil.encrypt(decrypt, key);
      System.out.println("AES加密后：" + encrypt);
      newPsw = encrypt;

    } catch (Exception e) {
      e.printStackTrace();
    }
    CustomerExample customerExample = new CustomerExample();
    CustomerExample.Criteria criteria = customerExample.createCriteria();
    criteria.andCustumerPswEqualTo(newPsw).andCustumerTelEqualTo(custumerTel.toString());
    List<Customer> customers = customerMapper.selectByExample(customerExample);
    //System.out.println(customers.get(0));
    System.out.println(customers.size());
    if (customers.size() != 0)  {
      System.out.println("login: cusId" + customers.get(0).getCustumerId());
      return ServerResult.loginSuccess(customers.get(0));
    }
    else return ServerResult.loginFail(null);
  }

  @Override
  public ServerResult regist(Customer customer) {
    //获得前端传来的用户密码
    String cusPwd = customer.getCustumerPsw();
    System.out.println("service--注册--前端加密后密码：" + cusPwd);
//    cusPwd = MD5Utils.formPwd2DBPass(cusPwd,"1a2b3c4d");
//    System.out.println("最终持久化到数据库中的密码是：" +cusPwd );
    //获得私钥
    String privateKey = getPrivateKey();

    try {
      System.out.println("RSA解密中。。。。");
      //原密码 = 解密方法（密文，私钥）
      String decrypted = RSAUtils.privateDecrypt(cusPwd, RSAUtils.getPrivateKey(privateKey));
      System.out.println("RSA解密后的密码：" + decrypted);

      // AES 加密
      String encrypt = AESUtil.encrypt(decrypted, key);
      System.out.println("AES加密后：" + encrypt);

      customer.setCustumerPsw(encrypt);
    } catch (Exception e) {
      e.printStackTrace();
    }



    int insert = customerMapper.insert(customer);
//    System.out.println("custId：" + customer.getCustumerId());
    if (insert > 0) return ServerResult.registSuccess(insert);
    else return ServerResult.registFail(null);

  }

  @Override
  public ServerResult getById(Integer cusId) {

    Customer customer = customerMapper.selectByPrimaryKey(cusId);
    if (customer != null) {
      System.out.println("server --  通过主键查询用户信息成功！" + customer);
      return ServerResult.getSuccess(customer);
    } else {
      System.out.println("server --  通过主键查询用户信息失败！");

      return ServerResult.getFail("通过主键查询用户信息失败");
    }

  }

  @Override
  public ServerResult update(Customer customer) {
    System.out.println("需要修改的customer id：" + customer.getCustumerId());
    int i = customerMapper.updateByPrimaryKeySelective(customer);
    System.out.println("i :" + i);
    if (i > 0) return ServerResult.putSuccess(i);
    else return ServerResult.putFail(null);
  }

  @Override
  public ServerResult getPublicKey(){

    //创建密钥对
    try {
      keyPair = RSAUtils.genKeyPair(1024);
      //获取公钥
      PublicKey publicKey = keyPair.getPublic();
      System.out.println("公钥：");

      String pubKey = new String(Base64.getEncoder().encode(publicKey.getEncoded()));
      System.out.println(pubKey);

      return ServerResult.getSuccess(pubKey);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return ServerResult.getFail(null);


  }

  @Override
  public String getPrivateKey() {

    PrivateKey privateKey = keyPair.getPrivate();
    System.out.println("get 私钥：");

    //输出String 私钥
    String priKey = new String(Base64.getEncoder().encode(privateKey.getEncoded()));
    System.out.println(priKey);

    return priKey;
  }
}
